﻿using System;
using ECommerce.Web.Models;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.AcceptanceCriteria;
using FluentNHibernate.Conventions.Inspections;
using FluentNHibernate.Conventions.Instances;

namespace ECommerce.Web.NHibernate.MappingConventions
{
    public class HasManyConvention : IHasManyConvention, IHasManyConventionAcceptance
    {
        public void Accept(IAcceptanceCriteria<IOneToManyCollectionInspector> criteria)
        {
            criteria.Expect(x => x.EntityType.BaseType == typeof(Entity) && !x.EntityType.IsAbstract);
        }
        
        public void Apply(IOneToManyCollectionInstance instance)
        {
            if (instance.Member.Name == "Children")
            {
                instance.Key.Column("ParentId");
            }

            instance.Inverse();
            instance.Access.CamelCaseField();
            instance.Cascade.AllDeleteOrphan();
            instance.Key.ForeignKey(String.Format("FK_{0}_{1}", instance.EntityType.Name, instance.ChildType.Name));
        }
    }
}
